[BITS 16]
;[O;RG 0x0500]
[ORG 0x0500]

	org	500h
;	org	0h

	cli
	xor	ax,	ax
	mov	ds,	ax
	mov	es,	ax
	mov	ax,	0x9000
	mov	ss,	ax
	mov	sp,	0xFFFF
	sti

;	xor	ax,	ax
;	mov	ds,	ax
;	mov	es,	ax
;	mov	ax,	0x9000
;	mov	ss,	ax
;	mov	sp,	0xFFFF
;	sti

	%include "include/defines.inc"

	mov	[disknum],	dl

;	mov	ah,	3
;	mov	dh,	0
;	call	printNum

; clear screen
	mov	ah, 	0h
	mov	al,	3h
	int	10h
	
;	mov	si,	welcome	; string pointer
;	call	printString	; print string

reset:	xor	ah,	ah	; function 0
	mov	dl,	[disknum]	; disk ID
	int	0x13		; reset disk
	jc	reset		; try again if failed

	mov	si,	loading	; string pointer
	call	printString	; print string

loadKernel:
	mov	dl,	[disknum]	; disk number
	mov	ah,	0x02	; read
	mov	al,	0x80	; 256 sectors * 512 bytes (131972 bytes / 128k)
	mov	ch,	0	; track
	mov	cl,	3	; sector
	mov	dh,	0	; head
	mov	bx,	KERNEL_SEG
	mov	es,	bx	; ... buffer segment
	mov	bx,	0x0000	; buffer start

	int	0x13		; read sector
	jc	loadKernel	; read again if failed

	mov	si,	booting	; string pointer
	call	printString	; print string

	mov	dl,	[disknum]

	mov	ax,	0xB800
	mov	gs,	ax

;	jmp	$

; update gdt
;	XOR	EAX, EAX
;	MOV	AX, DS
;	SHL	EAX, 4
;	ADD	EAX, gdt
;	MOV	[gdt_ptr + 2], eax
;	MOV	EAX, gdt_end
;	SUB	EAX, gdt
;	MOV	[gdt_ptr], AX
;	LGDT	[gdt_ptr]

	cli
	pusha
	lgdt	[gdt_ptr]
;	lgdt	0x1337
	popa
	sti

;	jmp	0000h:KERNEL_ENTRY
;	mov	ax,	0x7E0
	xor	eax,	eax
	mov	ds,	ax

	mov	ax,	0x7C00
	mov	sp,	ax

	mov	ax,	0x0000
	mov	ss,	ax

;	jmp	KERNEL_ENTRY:0000h
	jmp	KERNEL_SEG:0000



gdt:
	dd	0
	dd	0
code	equ	$-gdt
;	dd	0x0000FFFF,	0x00CF9A00	;   Kernel Code
	dw	0FFFFh
	dw	0
	db	0
	db	9Ah
	db	0CFh
	db	0
data	equ	$-gdt
;	dd	0x0000FFFF,	0x00CF9200	;   Kernel Data
	dw	0FFFFh
	dw	0
	db	0
	db	92h
	db	0CFh
	db	0

gdt_end:
gdt_ptr:
	dw	gdt_end - gdt - 1
	dd	gdt

idt:
	dw	0h
	dw	code
	db	0
	db	11100000b
	dw	0h



	loading	db	" # Loading kernel from hard disk...",13,10,0
	booting	db	" # Booting kernel...",13,10,0

	disknum	db	80h	; disk number
	
	%include "include/io.inc"

	times	510-($-$$) db 0	; fill to 440 bytes
	dw	0xAA55
